package com.igeekhome.ccs.config;

import com.igeekhome.ccs.entity.CustomerService;
import org.apache.ibatis.jdbc.Null;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import com.igeekhome.ccs.biz.Impl.CustomerServiceBizImpl;

import java.util.HashSet;
import java.util.Set;
import com.igeekhome.ccs.util.md5;
public class CustomRealm extends AuthorizingRealm {
    @Autowired
   CustomerServiceBizImpl csbi;
//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        获取用户名
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        CustomerService cs = csbi.getOneByUsername(username);

//        创建授权信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        Set<String> permissions = new HashSet<>();

        if(cs.getGroupName().equals("普通客服")){
            permissions.add("user:show");
        }
        else if (cs.getGroupName().equals("客服管理")){
            permissions.add("user:show");
            permissions.add("user:list");
        }
        else {
            // 超级管理员
            permissions.add("user:show");
            permissions.add("user:admin");
            permissions.add("user:list");
        }


        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String realpwd="8e964f4741121eea7f6dca01c409c282";

        String username = (String) authenticationToken.getPrincipal();

        CustomerService cs = csbi.getOneByUsername(username);
        if(cs==null){
            throw new AccountException("账号不存在");
        }
        String dbPwd = cs.getPassword();
        return new SimpleAuthenticationInfo(username,dbPwd, ByteSource.Util.bytes(username + "salt"),getName());

    }
}
